<script setup lang="ts">
import type { StatisticsBarProps } from '../type'
import { useChartTooltipTheme } from '@/mixins/MixinChartTooltipTheme'

const props = withDefaults(
  defineProps<StatisticsBarProps>(),
  {
    x() {
      return []
    },
    y() {
      return []
    },
    l() {
      return []
    },
    type: 'bar',
    seriesLayoutBy: 'row',
    showToolbox: false,
    showSeriesLabel: false,
  },
)

const dataset = computed<any>(() => {
  const xData = props.x
  const yData = props.y
  return {
    source: [
      ['时间', ...xData],
      ...props.l.map((_v, i) => ['值', ...yData.map(vv => vv[i])]),
    ],
  }
})
const tooltipTheme = useChartTooltipTheme()
const barOption = computed(() => ({
  legend: {
    show: true,
    data: props.l,
    type: 'scroll',
    // right: '100px',
    top: 3,
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
    ...tooltipTheme,
  },
  yAxis: {
    type: 'value',
  },
  xAxis: {
    type: 'category',
  },
  grid: {
    top: '24%',
    left: '2%',
    right: '4.5%',
    bottom: '3%',
    containLabel: true,
  },
  series: [
    ...props.l.map(v => ({
      name: v,
      type: props.type,
      // barMaxWidth: 60,
      seriesLayoutBy: props.seriesLayoutBy,
      label: {
        show: props.showSeriesLabel,
        formatter({ data, seriesIndex }: any) {
          const v = data
            .slice(1)
            .map((vv: string | number) => Number(vv) || 0)
          const total = v.reduce(
            (acc: number, vv: number) => {
              acc += vv
              return acc
            },
          )
          const value = v[seriesIndex]
          return total <= 0
            ? 0
            : `${((value * 100) / total).toFixed(2)}%`
        },
      },
      stack: String(props.type) === 'line' ? null : 'total',
    })),
  ],
  toolbox: {
    show: props.showToolbox,
    top: 0,
    feature: {
      // dataZoom: {
      //   yAxisIndex: 'none',
      //   title: {
      //     zoom: '区域缩放',
      //     back: '区域缩放还原'
      //   }
      // },
      // dataView: { readOnly: false, title: '数据视图' },
      magicType: {
        type: ['line', 'bar'],
        title: {
          line: '切换为折线图',
          bar: '切换为柱状图',
        },
      },
      // restore: {
      //   title: '还原'
      // },
      saveAsImage: {
        title: '保存为图片',
      },
    },
  },
}))
</script>

<template>
  <ViewChartBar
    :dataset="dataset"
    :option="barOption"
  />
</template>
